/**
 * 
 */
package com.siteseat.common.entity;

import org.apache.commons.lang3.StringUtils;

import com.siteseat.common.exception.InternalException;
import com.siteseat.common.misc.ClassHelper;

/**
 *
 */
public abstract class NamedEntity extends Entity {

  /**
   * 
   */
  private static final long serialVersionUID = -276888341260512843L;

  private Integer               id;

  private String            name;

  private String            label;

  private String            typeName;

  /**
   * @param that
   * @param includeCategories
   */
  public void cloneFrom( NamedEntity that ) {
    setId( that.getId() );
    setName( that.getName() );
    setLabel( that.getLabel() );
    this.typeName = that.getTypeName();
  }

  /**
   * @param typeName
   * @return
   */
  public final String getTypeName() {
    if( typeName == null ) {
      return ClassHelper.getClassTitle( getClass() );
    }
    return typeName;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void validate( ValidateLevel level ) {
    if( level.number >= ValidateLevel.MIDDLE.number ) {
      int t = getId().intValue();
      if( t <= 0 ) {
        throw new InternalException( "Invalid " + getTypeName() + " id. User id must > 0" );
      }
    }

    String n = getName();
    if( StringUtils.isEmpty( n ) ) {
      throw new InternalException( "Name cannot be empty, for " + getTypeName() + " with id=" + id );
    }
  }

  /**
   * Gets the name
   * 
   * @return the name
   */
  public String getName() {
    return name;
  }

  /**
   * Sets the name
   * 
   * @param name
   *          the name to set
   */
  public void setName( String name ) {
    this.name = name;
  }

  /**
   * @param id
   *          the id to set
   */
  public void setId( Integer id ) {
    this.id = id;
  }

  /**
   * @return the id
   */
  public Integer getId() {
    return id;
  }

  /**
   * Gets the label
   * 
   * @return the label
   */
  public String getLabel() {
    return label;
  }

  /**
   * Sets the label
   * 
   * @param label
   *          the label to set
   */
  public void setLabel( String label ) {
    this.label = label;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public boolean equals( Object that ) {
    if( that == null ) {
      return false;
    }
    if( that.getClass().isAssignableFrom( this.getClass() ) ) {
      return false;
    }
    String thisName = getName();
    String thatName = ( (NamedEntity)that ).getName();
    if( thisName == thatName ) {
      return true;
    }
    if( thisName == null ) {
      return false;
    }
    return thisName.equals( thatName );
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public int hashCode() {
    return getName().hashCode();
  }

}
